package thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockBank {

   static class User implements Runnable{
        private String name;
        private MyCount myCount;
        private int iocash;
        private Lock myLock;

        public  User(String name, MyCount myCount, int iocash, Lock myLock) {
            this.name = name;
            this.myCount = myCount;//账户
            this.iocash = iocash;//操作金额
            this.myLock = myLock;
        }

        @Override
        public void run() {
             myLock.lock();
             if (myCount.getCash()+iocash>0){
                 System.out.println(name+"正在操作"+myCount+"账户。金额为："+iocash+" 当前金额为："+myCount.getCash());
                 myCount.setCash(myCount.getCash()+iocash);
                 System.out.println(name+"操作"+myCount+"账户成功。金额为："+iocash+" 当前金额为："+myCount.getCash());
             }
             else {
                 System.out.println(name+"非法操作-----------");
             }
             myLock.unlock();
        }
    }
    public static void main(String[] args){
        MyCount myCount=new MyCount("09827672754",10000);
        Lock lock=new ReentrantLock();//一个可重入的互斥锁
        ExecutorService pool= Executors.newCachedThreadPool();

        User u1=new User("老大",myCount,-4000,lock);
        User u2=new User("老二",myCount,6000,lock);
        User u3=new User("老三",myCount,-8000,lock);
        User u4=new User("老四",myCount,-9000,lock);

        pool.execute(u1);
        pool.execute(u2);
        pool.execute(u3);
        pool.execute(u4);

        pool.shutdown();

    }
    static class MyCount{
        private String oid;
        private int cash;

        public MyCount(String oid, int cash) {
            this.oid = oid;
            this.cash = cash;
        }

        public String getOid() {
            return oid;
        }

        public void setOid(String oid) {
            this.oid = oid;
        }

        public int getCash() {
            return cash;
        }

        public void setCash(int cash) {
            this.cash = cash;
        }

        @Override
        public String toString() {
            return "MyCount{" +
                    "oid='" + oid + '\'' +
                    ", cash=" + cash +
                    '}';
        }
    }
}
